package com.example.demo2.controller;

import com.example.demo2.entity.*;
import com.example.demo2.mapper.CalHistoryMapper;
import com.example.demo2.request.CalculationRequest;
import com.example.demo2.service.*;
import com.example.demo2.service.impl.CalculationServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.util.*;

/**
 * 氨基酸控制器
 * 处理与氨基酸、计算、历史记录和结果相关的请求
 */
@RestController
@RequestMapping("/amino")
public class AminoController {
    private static final Logger logger = LoggerFactory.getLogger(AminoController.class);

    @Autowired
    private AminoService aminoService;

    @Autowired
    private UploadedDataService uploadedDataService;

    @Autowired
    private CalculationService calculationService;

    @Autowired
    private CalculationServiceImpl calculationServiceImpl;

    @Autowired
    private CalHistoryMapper calHistoryMapper;

    @Autowired
    private ResultService resultService;

    @Autowired
    private ExcelService excelService;

    @Autowired
    private ComparisonService comparisonService;

    @Autowired
    private ComparisonNameService comparisonNameService;

    @Autowired
    private ComparisonResultsService comparisonResultsService;
    /**
     * 获取所有氨基酸信息
     *
     * @param page 页码
     * @param size 每页大小
     * @return 氨基酸列表
     */
    @GetMapping("/all")
    public Map<String, Object> findAll(@RequestParam int page, @RequestParam int size) {
        List<Amino> aminos = aminoService.findAll(page, size);
        int totalAminos = aminoService.count(); // 获取总记录数

        Map<String, Object> response = new HashMap<>();
        response.put("data", aminos);
        response.put("totalPages", (int) Math.ceil((double) totalAminos / size));
        return response;
    }

    /**
     * 添加新的氨基酸
     *
     * @param amino 氨基酸信息
     * @return 添加结果消息
     */
    @PostMapping("/add")
    public ResponseEntity<String> addAmino(@RequestBody Amino amino) {
        aminoService.addAmino(amino);
        return ResponseEntity.ok("氨基酸添加成功！");
    }

    /**
     * 搜索氨基酸
     *
     * @param term 搜索关键字
     * @return 搜索结果
     */
    @GetMapping("/search")
    public List<Amino> searchAmino(@RequestParam String term) {
        return aminoService.searchAmino(term);
    }

    /**
     * 获取氨基酸的值
     *
     * @param name 氨基酸名称
     * @return 氨基酸值
     */
    @GetMapping("/value")
    public Amino getAminoValue(@RequestParam String name) {
        return aminoService.getAminoValue(name);
    }

    /**
     * 执行计算并保存结果
     *
     * @param request 计算请求
     * @return 计算完成消息
     */
    @PostMapping("/calculate")
    public ResponseEntity<String> calculate(@RequestBody CalculationRequest request) {
        calculationService.calculateAndSaveResults(request);
        return ResponseEntity.ok("计算成功完成");
    }

    /**
     * 获取计算进度
     *
     * @return 计算进度百分比
     */
    @GetMapping("/progress")
    public ResponseEntity<Integer> getProgress() {
        int progress = calculationServiceImpl.getProgress();
        int total = calculationServiceImpl.getTotalCombinations();
        int percentage = (int) ((progress / (double) total) * 100);
        return ResponseEntity.ok(percentage);
    }

    /**
     * 获取计算历史记录
     *
     * @return 计算历史列表
     */
    @GetMapping("/history")
    public ResponseEntity<List<CalHistory>> getCalHistory() {
        List<CalHistory> historyList = calHistoryMapper.getAllCalHistory();
        return ResponseEntity.ok(historyList);
    }

    /**
     * 获取计算结果
     *
     * @param formula 公式
     * @param page    页码
     * @param size    每页大小
     * @return 计算结果分页列表
     */
    @GetMapping("/results")
    public ResponseEntity<Page<Result>> getResults(
            @RequestParam String formula,
            @RequestParam String name,
            @RequestParam int page,
            @RequestParam int size) {
        System.out.println("Request received: formula=" + formula + ", name=" + name + ", page=" + page + ", size=" + size);
        Page<Result> results = resultService.getResultsByFormulaAndName(formula, name, page - 1, size);
        return ResponseEntity.ok(results);
    }


    @DeleteMapping("/delete/{id}")
    public String deleteAmino(@PathVariable Long id) {
        aminoService.deleteAmino(id);
        return "氨基酸删除成功";
    }

    @PostMapping("/upload")
    public ResponseEntity<String> uploadExcel(@RequestParam("file") MultipartFile file,@RequestParam("uploadName") String uploadName) {
        try {
            excelService.processExcel(file, uploadName);
            return ResponseEntity.ok("文件上传并处理成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件处理失败: " + e.getMessage());
        }
    }


    @GetMapping("/comparison-results")
    public ResponseEntity<?> getComparisonResultsByName(
            @RequestParam String name,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<ComparisonResults> results = comparisonService.getComparisonResults(name, page, size);
            return ResponseEntity.ok(results);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取比较结果失败");
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }


    @GetMapping("/uploaded-data")
    public ResponseEntity<List<Map<String, String>>> getAllUploadedData() {
        List<Map<String, String>> uploadedData = uploadedDataService.getAllUploadedDataNames();
        return ResponseEntity.ok(uploadedData);
    }

    @GetMapping("/uploaded-data/{uploadName}")
    public ResponseEntity<Page<UploadedData>> getUploadedDataByName(
            @PathVariable String uploadName,
            @RequestParam Optional<Integer> page,
            @RequestParam Optional<Integer> size) {
        int pageNumber = page.orElse(1);
        int pageSize = size.orElse(10);

        // 确保页码至少为1
        pageNumber = Math.max(1, pageNumber);

        Page<UploadedData> uploadedData = uploadedDataService.getUploadedDataByName(uploadName, pageNumber - 1, pageSize);
        return ResponseEntity.ok(uploadedData);
    }
    @PostMapping("/compare")
    public ResponseEntity<Map<String, String>> startComparison(@RequestBody Map<String, Object> request) {
        try {
            String resultName = (String) request.get("resultName");
            String uploadName = (String) request.get("uploadName");
            double tolerance = Double.parseDouble(request.get("tolerance").toString());
            String comparisonName = (String) request.get("comparisonName");

            String jobId = comparisonService.startComparison(resultName, uploadName, tolerance, comparisonName);

            Map<String, String> response = new HashMap<>();
            response.put("jobId", jobId);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", "比较开始失败: " + e.getMessage()));
        }
    }

    @GetMapping("/compare/progress/{jobId}")
    public ResponseEntity<Map<String, Integer>> getComparisonProgress(@PathVariable String jobId) {
        try {
            int progress = comparisonService.getProgress(jobId);

            Map<String, Integer> response = new HashMap<>();
            response.put("progress", progress);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", -1));
        }
    }
    @GetMapping("/result-names")
    public ResponseEntity<List<String>> getResultNames() {
        List<String> resultNames = resultService.getAllResultNames();
        return ResponseEntity.ok(resultNames);
    }

    @GetMapping("/upload-names")
    public ResponseEntity<List<String>> getUploadNames() {
        List<String> uploadNames = uploadedDataService.getAllUploadNames();
        return ResponseEntity.ok(uploadNames);
    }

    @GetMapping("/comparison-names")
    public ResponseEntity<List<ComparisonName>> getComparisonNames() {
        List<ComparisonName> names = comparisonNameService.getAllComparisonNames();
        return ResponseEntity.ok(names);
    }

    @GetMapping("/comparison-results/{comparisonName}")
    public ResponseEntity<Page<ComparisonResults>> getComparisonResultsDetailed(
            @PathVariable String comparisonName,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "100") int size) {
        Page<ComparisonResults> results = comparisonResultsService.getComparisonResultsByName(comparisonName, page, size);
        return ResponseEntity.ok(results);
    }

}